<template>
  <div class="p-4 mx-auto max-w-xl">
    <h2 class="mb-4 text-xl font-bold">正则表达式测试工具</h2>
    <input v-model="pattern" class="p-2 mb-2 w-full rounded border" placeholder="请输入正则表达式，如：^\\d+$" />
    <input v-model="testString" class="p-2 mb-4 w-full rounded border" placeholder="请输入待测试字符串" />
    <div class="mb-2 text-sm text-gray-600">匹配结果：</div>
    <div class=" p-2 rounded border min-h-[40px]">
      <span v-if="error" class="text-red-500">{{ error }}</span>
      <span v-else-if="matches.length">{{ matches.join(', ') }}</span>
      <span v-else>无匹配</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
const pattern = ref('\\d+')
const testString = ref('abc123def456gh789')
const matches = ref<string[]>([])
const error = ref('')

watch([pattern, testString], () => {
  error.value = ''
  matches.value = []
  if (!pattern.value || !testString.value) return
  try {
    const reg = new RegExp(pattern.value, 'g')
    matches.value = testString.value.match(reg) || []
  } catch (e) {
    error.value = '正则表达式无效'
  }
})
</script>